import { app, shell, BrowserWindow, ipcMain, globalShortcut, nativeTheme } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../resources/icon.png?asset'
import { registerShellIPC, shellService } from './shellService'
import { pathService, registerPathIPC } from './pathService'
import { registerWindowIPC, windowService } from './windowService'
import { nodeService, registerNodeIpc } from './nodeService'
import { checkUpdate } from './update'
import log from 'electron-log'
import { notificationServices, registerNotificationIPC } from './notificationServices'
import { mainWindowConfig } from './config'
import { fileService, registerFileIPC } from './fileService'
import { registerRequestIPC, requestService } from './requestService'

import { init } from '@sentry/electron/main';
import { damaService, registerDamaIPC } from './damaPlatform1'

init({
  dsn: "https://8cc4dd31916ed03b14026fb12635594c@o4510004440727552.ingest.de.sentry.io/4510004516028496",
  // 建议添加的额外配置
  environment: process.env.NODE_ENV || 'production',
  release: app.getVersion(),
  tracesSampleRate: 0.2  // 性能监控采样率
})


function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow(mainWindowConfig)

  nativeTheme.themeSource = 'dark'

  try {
    checkUpdate(mainWindow)
  } catch (error) {
    log.error(error)
  }

  // 设置DevTools快捷键
  globalShortcut.register('CommandOrControl+Shift+i', function () {
    mainWindow.webContents.openDevTools()
  })


  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'allow' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // 在页面加载完成后注入版本信息
  mainWindow.webContents.once('dom-ready', () => {
    const version = app.getVersion()
    mainWindow.webContents.executeJavaScript(`
      window.APP_VERSION = '${version}';
    `)
  })
}


app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.lidong')
  createWindow()

  // myUndefinedFunction();
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  app.on('activate', function () {

  })
})


app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})



registerShellIPC(shellService)
registerPathIPC(pathService)
registerWindowIPC(windowService)
registerNodeIpc(nodeService)
registerFileIPC(fileService)
registerRequestIPC(requestService)

registerNotificationIPC(notificationServices)
registerDamaIPC(damaService)